package com.controller;

import java.text.MessageFormat;
import java.util.*;
import java.util.logging.Logger;

import com.alibaba.fastjson.JSONArray;
import com.util.JsoupUtils;
import org.apache.commons.lang3.StringUtils;
//import org.jsoup.Connection;
//import org.jsoup.Jsoup;
//import org.jsoup.nodes.Document;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.param.dto.ParamDataDto;
import com.param.util.ParamConstants;
import com.param.util.ParamUtil;
import com.param.util.ParseDataUtil;
import com.util.MesJson;
import com.util.Result;

/**
 * 获取参数比对数据
 * @author Administrator
 *
 */
@CrossOrigin
@RestController
@RequestMapping("/param")
public class ParamController {
	
	/**
	 * 获取2.0设备参数比对数据
	 * @param jsonData
	 * @return
	 */
	@RequestMapping(value="/getParamData",method = RequestMethod.POST,produces = "application/json")
	public Result<String> getSocketData(@RequestBody String jsonData) {
		Result<String> result  = new Result<String>();
		result.setCode(0);
		result.setMsg("获取参数数据失败！");
		MesJson mesJson = null;
		List<ParamDataDto> array = null;
		Map<String,Object> extend = null;
		String isFormat = null;
		try {
			mesJson = JSONObject.parseObject(jsonData,MesJson.class);
			System.out.println("===入参===>："+mesJson.getData());
			extend = JSONObject.parseObject(mesJson.getExtend(),Map.class);
		    array = JSONObject.parseArray(mesJson.getData(),ParamDataDto.class);
			isFormat = (String) extend.get("isFormat");
			if(array.isEmpty()&&StringUtils.isEmpty(isFormat)) {
				result.setMsg("无参数比对数据");
				return result;
			}
			//排序参数数据
			//array.sort(Comparator.comparing(ParamDataDto::getSeq));
		}catch(Exception e) {
			e.printStackTrace();
			result.setMsg("解析JSON格式数据异常！");
			return result;
		}

		String userName = (String) extend.get("userName");
		String  password = (String) extend.get("passWord");
		String ip = (String) extend.get("ip");
		String loginUrl = ParamConstants.LOGIN_URL;
		loginUrl = MessageFormat.format(loginUrl, ip);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,String> cookiesMap = ParamUtil.getCookiesMap(loginUrl, userName, password,1,1);
		if (cookiesMap.size()==0){
			result.setMsg("登录网页出错，请确认交互配置中的账号密码是否和设备的一致");
			return result;
        }
		Map<String,Object> disSeq = new HashMap<String,Object>();

		//区分两套业务
		if(StringUtils.isNotEmpty(isFormat) && isFormat.equals("Y")){
			//格式化的内容
			result = whetherFormat(cookiesMap,ip);
		}else {
			//之前的业务 参数比对的内容
			result = compareParams(cookiesMap,ip,array,disSeq);
		}
		return result;
	}


	private Result<String>  whetherFormat(Map<String,String> cookiesMap,String ip){
		Result<String> result  = new Result<String>();
		//找到所有的存储器的id
		String devUrl = ParamConstants.DEV_INFO;
		devUrl = MessageFormat.format(devUrl, ip);
		List<String> devs = ParamUtil.getDevsInfo(cookiesMap,devUrl);
		//下达格式化命令
		String allFormatUrl = ParamConstants.ALL_FORMAT;
		allFormatUrl = MessageFormat.format(allFormatUrl, ip);
		System.out.println("开始格式化");
		result = ParamUtil.formatAllDev(cookiesMap,allFormatUrl,devs);
		return result;
	}

	private Result<String> compareParams(Map<String,String> cookiesMap,String ip,List<ParamDataDto> array,Map<String,Object> disSeq){
		Map<String,Object> resultMap = new HashMap<>();
		Result<String> result  = new Result<String>();
		//获取服务器信息：已验证
		String serverUrl = ParamConstants.SERVER_URL;
		serverUrl = MessageFormat.format(serverUrl, ip);
		System.out.println("获取服务器信息：" + serverUrl + ".....");
		ParamUtil.getServerData(cookiesMap,serverUrl,resultMap);


		//由于串口不存在启用关闭情况，获取关闭的port并在port获取数据时候需要重算序号

		List<Integer> disableSeq = new ArrayList<>();
		for (ParamDataDto paramDataDto : array) {
			String code = paramDataDto.getCode();
			String[] codeArr = code.split("-");
			if(!codeArr[0].equals("port")) {
				continue;
			}
			if(paramDataDto.getValue().equals("off")) {
				Integer seq = Integer.parseInt(codeArr[1]);
				disableSeq.add(seq);
			}
		}
		disSeq.put("port", disableSeq);
		//串口数据：已验证
		String portUrl = ParamConstants.PORT_URL;
		serverUrl = MessageFormat.format(portUrl, ip);
		System.out.println("串口数据：" + serverUrl + ".....");
		ParamUtil.getPortData(cookiesMap,serverUrl,resultMap);


		//串口报警：已验证
		String portAlarmUrl = ParamConstants.PORTALARM_URL;
		portAlarmUrl = MessageFormat.format(portAlarmUrl, ip);
		System.out.println("串口报警：" + portAlarmUrl + ".....");
		ParamUtil.getPortAlarmData(cookiesMap,portAlarmUrl,resultMap);

		//获取音频信息，已验证
		String audioUrl = ParamConstants.AUDIO_URL;
		audioUrl = MessageFormat.format(audioUrl, ip);
		System.out.println("获取音频信息：" + audioUrl + ".....");
		ParamUtil.getAudioData(cookiesMap,audioUrl,resultMap);

		//获取制式
		String audioUrlForZs = ParamConstants.AUDIO_URL;
		audioUrlForZs = MessageFormat.format(audioUrlForZs, ip);
		System.out.println("获取制式：" + audioUrlForZs + ".....");
		ParamUtil.getAudioZsData(cookiesMap,audioUrlForZs,resultMap);

		// 获取AI报警
		String alarmUrl = ParamConstants.ALARM_URL;
		alarmUrl = MessageFormat.format(alarmUrl, ip);
		System.out.println("获取AI报警：" + alarmUrl + ".....");
		ParamUtil.getAlarmData(cookiesMap,alarmUrl,resultMap);


		//通讯模块
		String comunicationUrl = ParamConstants.COMMUNICATION_URL;
		comunicationUrl = MessageFormat.format(comunicationUrl, ip);
		System.out.println("通讯模块：" + comunicationUrl + ".....");
		ParamUtil.getAllCommunicationData(cookiesMap,comunicationUrl,resultMap);

		//智能应用
		String intelligenceUrl = ParamConstants.INTELLIGENCE_URL;
		intelligenceUrl = MessageFormat.format(intelligenceUrl, ip);
		System.out.println("智能应用：" + intelligenceUrl + ".....");
		ParamUtil.getIntelligenceData(cookiesMap,intelligenceUrl,resultMap);

		//注册信息 出厂序列号
		String registrationUrl = ParamConstants.REGISTRATION_URL;
		registrationUrl = MessageFormat.format(registrationUrl, ip);
		System.out.println("注册信息：" + registrationUrl + ".....");
		ParamUtil.getRegistrationData(cookiesMap,registrationUrl,resultMap,array);

		//有线网络 MAC地址
		String wireUrl = ParamConstants.WIRE_URL;
		wireUrl = MessageFormat.format(wireUrl, ip);
		System.out.println("有线：" + wireUrl + ".....");
		ParamUtil.getWireMacData(cookiesMap,wireUrl,resultMap);
		System.out.println("======>获取到的数据信息汇总："+JSONObject.toJSONString(resultMap));

		if(resultMap.isEmpty()) {
			result.setMsg("未获取到网页数据信息！");
			return result;
		}
		ParseDataUtil.getParamDataFromList(array,resultMap,disSeq);
		result.setCode(1);
		result.setMsg("获取参数数据成功！");
		result.setData(JSONObject.toJSONString(array));
		return result;
	}


	/**
	 * 获取1.0设备参数比对数据
	 * @param jsonData
	 * @return
	 */
	@RequestMapping(value="/getParamDataV1",method = RequestMethod.POST,produces = "application/json")
	public Result<String> getParamDataV1(@RequestBody String jsonData) {
		Result<String> result  = new Result<String>();
		result.setCode(0);
		result.setMsg("获取1设备参数数据失败！");
		MesJson mesJson = null;
		List<ParamDataDto> array = null;
		Map<String,Object> extend = null;
		try {
			mesJson = JSONObject.parseObject(jsonData,MesJson.class);
			System.out.println("===入参===>："+mesJson.getData());
			extend = JSONObject.parseObject(mesJson.getExtend(),Map.class);
			array = JSONObject.parseArray(mesJson.getData(),ParamDataDto.class);
			if(array.isEmpty()) {
				result.setMsg("无参数比对数据");
				return result;
			}
			//排序参数数据
			//array.sort(Comparator.comparing(ParamDataDto::getSeq));
		}catch(Exception e) {
			e.printStackTrace();
			result.setMsg("解析JSON格式数据异常！");
			return result;
		}
		String userName = (String) extend.get("userName");
		String  password = (String) extend.get("passWord");
		String ip = (String) extend.get("ip");
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String loginUrl = ParamConstants.LOGIN_URL_V1;
		loginUrl = MessageFormat.format(loginUrl, ip);
		Map<String,String> cookiesMap = ParamUtil.getCookiesMapV1(loginUrl, userName, password,1,1);
		if (cookiesMap.size()==0){
			result.setMsg("登录网页出错，请确认交互配置中的账号密码是否和设备的一致");
			return result;
        }
		//获取服务器信息：已验证
		String url = MessageFormat.format(ParamConstants.URL_V1, ip);
		ParamUtil.getServerDataV1(cookiesMap,url,resultMap);


		//由于串口不存在启用关闭情况，获取关闭的port并在port获取数据时候需要重算序号
		Map<String,Object> disSeq = new HashMap<String,Object>();
		List<Integer> disableSeq = new ArrayList<>();
		for (ParamDataDto paramDataDto : array) {
			String code = paramDataDto.getCode();
			String[] codeArr = code.split("-");
			if(!codeArr[0].equals("port")) {
				continue;
			}
			if(paramDataDto.getValue().equals("off")) {
				Integer seq = Integer.parseInt(codeArr[1]);
				disableSeq.add(seq);
			}
		}
		disSeq.put("port", disableSeq);
		//串口数据：已验证
		ParamUtil.getPortDataV1(cookiesMap,url,resultMap);

		//串口报警：已验证
		ParamUtil.getPortAlarmDataV1(cookiesMap,url,resultMap);

		//获取音频信息，已验证
		ParamUtil.getAudioDataV1(cookiesMap,url,resultMap);

		//获取制式
		ParamUtil.getAudioZsDataV1(cookiesMap,url,resultMap);

		// 获取AI报警
		ParamUtil.getAlarmDataV1(cookiesMap,url,resultMap);

		//通讯模块
		ParamUtil.getAllCommunicationDataV1(cookiesMap,url,resultMap);

		System.out.println("======>获取到的数据信息汇总："+JSONObject.toJSONString(resultMap));


		if(resultMap.isEmpty()) {
			result.setMsg("未获取到网页数据信息！");
			return result;
		}

		ParseDataUtil.getParamDataFromList(array,resultMap,disSeq);
		result.setCode(1);
		result.setMsg("获取参数数据成功！");
		result.setData(JSONObject.toJSONString(array));
		return result;


	}
	
}
